package com.yy.main.app.web;

import com.alibaba.fastjson.JSONObject;
import com.yy.kit.annotation.HasPers;
import com.yy.kit.collections.YYMapKits;
import com.yy.kit.string.YYStrKits;
import com.yy.main.app.mapper.TPermissionMapper;
import com.yy.main.app.mapper.TRolePermissionMapper;
import com.yy.main.app.service.IPermissionService;
import com.yy.main.app.service.IRolePermissionService;
import com.yy.main.app.web.base.CommonController;
import com.yy.pojo.base.TPermission;
import com.yy.pojo.base.TPermissionExample;
import com.yy.pojo.base.TRolePermissionExample;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 权限前端控制器
 * </p>
 *
 * @author 杨阳
 * @since 2017-08-22
 */
@Controller
@RequestMapping("/permission")
@Api(value = "权限controller", tags = {"权限controller"})
public class PermissionController extends CommonController {

    @Resource(name = "iPermissionService")
    private IPermissionService iPermissionService;
    @Resource(name = "iRolePermissionService")
    private IRolePermissionService iRolePermissionService;
    @Autowired
    private TPermissionMapper tPermissionMapper;
    @Autowired
    private TRolePermissionMapper tRolePermissionMapper;


    /**
     * <p>
     * 跳转到权限管理页面
     * </p>
     *
     * @return {@link ModelAndView}
     * @author 杨阳
     * @since 2017年9月11日
     */
    @RequestMapping(value = "/permissionList", method = RequestMethod.GET)
    @HasPers(name = "pers:manager")
    @ApiOperation(value = "跳转到权限管理页面", httpMethod = "GET", notes = "跳转到权限管理页面,需要拥有pers:manager权限")
    public ModelAndView permissionList(HttpSession session) {
        return goToPageByModelAndView("system/permission/permission_list", null, getCurrentUser(session).getId());
    }

    /**
     * <p>
     * 获得权限管理异步树
     * </p>
     *
     * @param id 节点id，也是权限id
     * @return {@link List<TPermission>}
     * @author 杨阳
     * @since 2017年9月11日
     */
    @ApiOperation(value = "获得权限管理异步树", httpMethod = "POST", notes = "获得权限管理异步树")
    @RequestMapping(value = "/tree", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "权限ID,第一次请求根节点，id肯定为空，第二次请求才会有值")
    })
    public void tree(String id, HttpSession session, HttpServletResponse response) {
        List<TPermission> perList = iPermissionService.getUserPersManageTree(id, getCurrentUser(session).getId());
        System.out.println(JSONObject.toJSONString(perList));
        try {
            response.getWriter().write(JSONObject.toJSONString(perList));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * <p>
     * 获取权限树，根据角色ID，默认勾选上角色已经拥有的权限
     * </p>
     *
     * @return {@link List<TPermission>}
     * @author 杨阳
     * @since 2017年9月13日
     */
    @RequestMapping(value = "/roleAlreadyHavePermissions/{roleid}", method = RequestMethod.POST)
    @ApiOperation(value = "获取权限树", httpMethod = "POST", notes = "根据角色ID，默认勾选上角色已经拥有的权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleid", value = "角色ID", required = true, paramType = "path"),
            @ApiImplicitParam(name = "id", value = "权限ID", paramType = "query")
    })
    public @ResponseBody
    List<TPermission> roleAlreadyHavePermissions(@PathVariable("roleid") String roleid, String id) {
        return iPermissionService.roleAlreadyHavePermissions(id, roleid);
    }

    /**
     * <p>
     * 获得权限的详细信息
     * </p>
     *
     * @param id 权限id
     * @author 杨阳
     * @since 2017年9月12日
     */

    @RequestMapping(value = "/get/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "获得权限的详细信息", httpMethod = "POST", notes = "获得权限的详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "权限ID", required = true, paramType = "path")
    })
    @ResponseBody
    public TPermission get(@PathVariable("id") String id) {
        return tPermissionMapper.selectByPrimaryKey(id);
    }

    /**
     * <p>
     * 跳转到增加、修改权限的表单页面
     * </p>
     *
     * @param id 权限id
     * @return {@link ModelAndView}
     * @author 杨阳
     * @since 2017年9月12日
     */
    @RequestMapping(value = "/permissionform/{id}/{parentid}", method = RequestMethod.GET)
    @HasPers(name = "permission:add,permission:update")
    @ApiOperation(value = "跳转到增加、修改权限的表单页面", httpMethod = "GET", notes = "跳转到增加、修改权限的表单页面，需要拥有permission:add,permission:update权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "权限ID，如果是增加id肯定为-1", required = true)
    })
    public ModelAndView permissionForm(@PathVariable("id") String id, @PathVariable("parentid") String parentid) {
        TPermission permission = new TPermission();
        if (!"-1".equals(id)) {
            // 增加
            permission = tPermissionMapper.selectByPrimaryKey(id);
        } else {
            permission.setParentid(parentid);
            permission.setId(id);
        }
        Map<String, Object> params = YYMapKits.createHashMap();
        params.put("permission", permission);
        return goToPageByModelAndView("system/permission/permission_form", params);
    }

    /**
     * <p>
     * 增加或修改权限
     * </p>
     *
     * @param permission 权限实体类
     * @return {@link Map}
     * @author 杨阳
     * @since 2017年9月12日
     */
    @RequestMapping(value = "/savepermission", method = RequestMethod.POST)
    @ApiOperation(value = "保存权限信息", httpMethod = "POST", notes = "增加或修改操作")
    @ResponseBody
    public Map<String, Object> savepermission(TPermission permission) {
        Map<String, Object> map = YYMapKits.createHashMap();
        // 修改或保存权限
        if ("-1".equals(permission.getId())) {
            // 增加
            permission.setId(YYStrKits.getTableId());
            Integer b = tPermissionMapper.insert(permission);
            if (b > 0) {
                map.put("success", Boolean.TRUE);
                map.put("msg", "增加权限成功!");
            } else {
                map.put("success", Boolean.FALSE);
                map.put("msg", "增加权限失败,请重试!");
            }
        } else {// 修改
            Integer b = tPermissionMapper.updateByPrimaryKey(permission);
            if (b > 0) {
                map.put("success", Boolean.TRUE);
                map.put("msg", "修改权限成功!");
            } else {
                map.put("success", Boolean.FALSE);
                map.put("msg", "修改权限失败,请重试!");
            }
        }
        return map;
    }

    /**
     * <p>
     * 删除权限
     * </p>
     *
     * @param id 权限id
     * @return {@link Map}
     * @author 杨阳
     * @since 2017年9月12日
     */
    @RequestMapping(value = "/delpermission/{id}", method = RequestMethod.POST)
    @HasPers(name = "permission:delete")
    @ApiOperation(value = "删除权限", httpMethod = "POST", notes = "删除权限，需要拥有permission:delete权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "权限ID", required = true, paramType = "path")
    })
    @ResponseBody
    public Map<String, Object> delete(@PathVariable("id") String id) {
        Map<String, Object> map = YYMapKits.createHashMap();
        // 判断当前选中的节点有没有子节点
        TPermissionExample perW = new TPermissionExample();
        perW.createCriteria().andParentidEqualTo(id);
        long count = tPermissionMapper.countByExample(perW);

        if (count > 0) {
            map.put("success", Boolean.FALSE);
            map.put("msg", "要删除的权限包含子节点,不可以删除!");
            return map;
        } else {
            // 判断是否与某个角色相关联
            TRolePermissionExample rpW = new TRolePermissionExample();
            rpW.createCriteria().andPermissions_idEqualTo(id);
            count = tRolePermissionMapper.countByExample(rpW);
            if (count > 0) {
                map.put("success", Boolean.FALSE);
                map.put("msg", "要删除的权限与角色相关联,不可以删除!");
                return map;
            } else {
                Integer b = tPermissionMapper.deleteByPrimaryKey(id);
                if (b > 0) {
                    map.put("success", Boolean.TRUE);
                    map.put("msg", "删除权限成功!");
                    return map;
                } else {
                    map.put("success", Boolean.FALSE);
                    map.put("msg", "删除权限失败,请重试!");
                    return map;
                }
            }
        }
    }
}
